import { getPhoneCode } from "@/api/modules/user";
import { showMsg } from "@/utils/util";

export const usePhoneCode = (detail: { mobile?: string; email?: string; [key: string]: any }) => {
	const state = reactive<any>({
		countDown: 0,
		codeInterval: null,
		codeLoading: false,
		errMsg: ""
	});
	const getCode = async (mobile?: string) => {
		detail.mobile = detail.mobile || mobile;
		if (!detail.mobile) {
			showMsg("请输入手机号", false);
			return;
		}
		if (!/^1[3456789]\d{9}$/.test(detail.mobile)) {
			showMsg("手机号码有误", false);
			return;
		}
		state.countDown = 60;
		try {
			await getPhoneCode({ identifier: detail.mobile });
			state.codeInterval = window.setInterval(() => {
				if (state.countDown <= 0) {
					clearCountDown();
					state.countDown = 0;
					return;
				}
				state.countDown -= 1;
			}, 1000);
		} catch (e) {
			console.error(e);
			state.countDown = 0;
		}
	};
	const clearCountDown = () => {
		if (state.codeInterval) {
			window.clearInterval(state.codeInterval);
		}
	};
	onBeforeUnmount(() => {
		clearCountDown();
	});
	return {
		codeStatus: state,
		getCode
	};
};
